<template>
  <div>
    <vm-status v-if="showStatus"
               emptyText="还没有农场"></vm-status>

    <scroller :show-scrollbar="false"
              v-else>

      <text class="farm-title">{{farm.farmName}}生产分析</text>
      <text class="cate-title">投料</text>
      <div class="flex-row bg-white px-1">
        <text v-for="(btn, index) in dayBtns"
              :key="index"
              :class="['cate-btn', forageBtnIndex === index && 'cate-btn-active']"
              @click="toggleForage(index, btn.days)">{{btn.label}}</text>
      </div>
      <bmchart :options="forageOption"
               style="width:750; height:560;"></bmchart>

      <text class="cate-title">死淘率</text>
      <div class="flex-row bg-white px-1">
        <text v-for="(btn, index) in dayBtns"
              :key="index"
              :class="['cate-btn', dieeliBtnIndex === index && 'cate-btn-active']"
              @click="toggleDieEli(index, btn.days)">{{btn.label}}</text>
      </div>
      <bmchart :options="dieeliOption"
               style="width:750; height:560;"></bmchart>

      <text class="cate-title">鸡均重</text>
      <div class="flex-row bg-white px-1">
        <text v-for="(btn, index) in weekBtns"
              :key="index"
              :class="['cate-btn', chickBtnIndex === index && 'cate-btn-active']"
              @click="toggleChickWeight(index, btn.days)">{{btn.label}}</text>
      </div>
      <bmchart :options="chickWeightOption"
               style="width:750; height:560;"></bmchart>

      <text class="cate-title">蛋均重</text>
      <div class="flex-row bg-white px-1">
        <text v-for="(btn, index) in weekBtns"
              :key="index"
              :class="['cate-btn', eggBtnIndex === index && 'cate-btn-active']"
              @click="toggleEggWeight(index, btn.days)">{{btn.label}}</text>
      </div>
      <bmchart :options="eggWeightOption"
               style="width:750; height:560;"></bmchart>

    </scroller>

  </div>
</template>

<script>
import VmStatus from '../../components/vm-status.vue'
import {
  STORAGE_FARM
} from '../../plugins/constant'

export default {
  components: { VmStatus },
  props: {},
  data: () => ({
    showStatus: false,
    farm: {},
    related: {},
    dayBtns: [
      { label: '近7天', days: 7 },
      { label: '近30天', days: 30 },
      { label: '近60天', days: 60 }
    ],
    forageBtnIndex: 0,
    forageOption: {},
    dieeliBtnIndex: 0,
    dieeliOption: {},
    weekBtns: [
      { label: '近4周', days: 7 * 4 },
      { label: '近8周', days: 7 * 8 },
      { label: '近12周', days: 7 * 12 }
    ],
    chickBtnIndex: 0,
    chickWeightOption: {},
    eggBtnIndex: 0,
    eggWeightOption: {},
  }),
  computed: {},
  watch: {},
  created() {
    this.getFarmInfo()
  },
  methods: {
    getFarmInfo() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      console.log(JSON.stringify(this.farm))
      if (this.farm.id) {
        this.getData()
      } else {
        this.showStatus = true
      }
    },

    getData() {
      this.getForageAnalysisDay()
      this.getDieEliAnalysisDay()
      this.getChickAnalysisWeek()
      this.getEggAnalysisWeek()
    },

    getForageAnalysisDay({
      startDate = this.getDateDelta(7),
      endDate = this.getDateDelta()
    } = {}) {
      this.fetchAndSetData({
        query: [
          'groupFunc=AVG(product_analysis_day_view.avg_feed_dosage)',
          'groupFields=day_age',
          'fields=day_age',
          'fields=gs_feed_dosage'
        ],
        table: 'product_analysis_day_view',
        xKey: 'day_age',
        aKey: 'p',
        bKey: 'gs_feed_dosage',
        option: 'forageOption',
        title: `${this.farm.farmName}投料分析`,
        legend: ['用料量', '标准量'],
        xText: '日龄',
        yText: '千克',
        startDate,
        endDate
      })
    },

    getDieEliAnalysisDay({
      startDate = this.getDateDelta(7),
      endDate = this.getDateDelta()
    } = {}) {
      this.fetchAndSetData({
        query: [
          'groupFunc=AVG(product_analysis_day_view.die_eli_rate)',
          'groupFields=day_age',
          'fields=day_age',
          'fields=gs_die_eli_rate'
        ],
        table: 'product_analysis_day_view',
        xKey: 'day_age',
        aKey: 'p',
        bKey: 'gs_die_eli_rate',
        option: 'dieeliOption',
        title: `${this.farm.farmName}死淘率分析`,
        legend: ['实际值', '标准值'],
        xText: '日龄',
        yText: '羽',
        startDate,
        endDate
      })
    },

    getChickAnalysisWeek({
      startDate = this.getDateDelta(7 * 4),
      endDate = this.getDateDelta()
    } = {}) {
      this.fetchAndSetData({
        query: [
          'groupFunc=AVG(product_analysis_week_view.avg_weight)',
          'groupFields=weeks',
          'fields=weeks',
          'fields=gs_avg_weight'
        ],
        table: 'product_analysis_week_view',
        xKey: 'weeks',
        aKey: 'p',
        bKey: 'gs_avg_weight',
        option: 'chickWeightOption',
        title: `${this.farm.farmName}鸡均重分析`,
        legend: ['实际值', '标准值'],
        xText: '周',
        yText: '千克',
        startDate,
        endDate
      })
    },

    getEggAnalysisWeek({
      startDate = this.getDateDelta(7 * 4),
      endDate = this.getDateDelta()
    } = {}) {
      this.fetchAndSetData({
        query: [
          'groupFunc=AVG(product_analysis_week_view.egg_avg_weight)',
          'groupFields=weeks',
          'fields=weeks',
          'fields=gs_egg_avg_weight'
        ],
        table: 'product_analysis_week_view',
        xKey: 'weeks',
        aKey: 'p',
        bKey: 'gs_egg_avg_weight',
        option: 'eggWeightOption',
        title: `${this.farm.farmName}蛋均重分析`,
        legend: ['实际值', '标准值'],
        xText: '周',
        yText: '克',
        startDate,
        endDate
      })
    },

    toggleForage(index, days) {
      this.forageBtnIndex = index
      this.getForageAnalysisDay({
        startDate: this.getDateDelta(days),
        endDate: this.getDateDelta()
      })
    },
    toggleDieEli(index, days) {
      this.dieeliBtnIndex = index
      this.getDieEliAnalysisDay({
        startDate: this.getDateDelta(days),
        endDate: this.getDateDelta()
      })
    },
    toggleChickWeight(index, days) {
      this.chickBtnIndex = index
      this.getChickAnalysisWeek({
        startDate: this.getDateDelta(days),
        endDate: this.getDateDelta()
      })
    },
    toggleEggWeight(index, days) {
      this.eggBtnIndex = index
      this.getEggAnalysisWeek({
        startDate: this.getDateDelta(days),
        endDate: this.getDateDelta()
      })
    },

    async fetchAndSetData({ query = [], table, xKey, aKey, bKey, option, title, legend, xText, yText, startDate, endDate }) {
      // query.push(`where=${encodeURIComponent(`"${table}.supplier_id".eq(${this.farm.id})`)}`)
      query.push(`where=${encodeURIComponent(`"${table}.log_time".lte(${endDate})`)}`)
      query.push(`where=${encodeURIComponent(`"${table}.log_time".gte(${startDate})`)}`)
      this.$notice.loading.show()
      const [res, err] = await this.$utils.pm(this.$api.getDataQuery({
        server: 'agr_chain',
        table,
        query: `?${query.join('&')}`,
        errorMsg: '获取数据失败'
      }))
      this.$notice.loading.hide()
      const data = this.getResultArray(res)
      const xData = []
      const aData = []
      const bData = []
      for (const d of data) {
        xData.push(d[xKey] || '-')
        aData.push(this.pureZero(d[aKey]))
        bData.push(this.pureZero(d[bKey]))
      }
      this.setOption({ option, title, legend, xData, aData, bData, xText, yText })
    },

    setOption({ option, title = '', legend = ['', ''], xData, aData, bData, xText, yText }) {
      if (!option) { return }
      this.$set(this, option, this.$format({
        title: {
          text: title,
          left: 'center',
          top: 30
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: legend,
          top: 60
        },
        grid: {
          top: 120,
          left: 50,
          right: 50
        },
        xAxis: [{
          type: 'category',
          data: xData,
          name: xText,
          axisLine: {
            lineStyle: {
              color: '#42bd56'
            }
          },
          splitLine: {
            lineStyle: {
              color: ['#eee']
            }
          }
        }],
        yAxis: [{
          type: 'value',
          name: yText,
          axisLine: {
            lineStyle: {
              color: '#42bd56'
            }
          },
          splitLine: {
            lineStyle: {
              color: ['#eee']
            }
          }
        }],
        series: [{
          name: legend[0],
          type: 'line',
          data: aData,
          smooth: true
        }, {
          name: legend[1],
          type: 'line',
          data: bData,
          smooth: true
        }]
      }))
    },

    getResultArray(res) {
      return res || []
    },
    pureZero(num) {
      return num ? Number.parseFloat(num) : 0
    },
    getDateDelta(delta = 0) {
      return this.$utils.dateFormat(new Date(+new Date() - 8.64e7 * delta), 'yyyy-MM-dd')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.text-muted {
  color: #999;
}
.text-accent {
  color: $accent-light;
}
.bg-white {
  background-color: #fff;
}
.small {
  font-size: 26px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mb-2 {
  margin-bottom: 20px;
}
.mb-3 {
  margin-bottom: 30px;
}
.mt-3 {
  margin-top: 30px;
}
.p-3 {
  padding: 30px;
}
.p-2 {
  padding: 20px;
}
.p-1 {
  padding: 10px;
}
.pb-2 {
  padding-bottom: 20px;
}
.px-1 {
  padding-left: 10px;
  padding-right: 10px;
}
.pt-3 {
  padding-top: 30px;
}

.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.text-center {
  text-align: center;
}
.text-lg {
  font-size: 34px;
}
.align-center {
  align-items: center;
}
.border-bottom {
  border-bottom-color: $border-color;
  border-bottom-width: 1px;
}
.border-top {
  border-top-color: $border-color;
  border-top-width: 1px;
}

.farm-title {
  text-align: center;
  padding: 30px;
  background-color: #fff;
  font-size: 32px;
  font-weight: bold;
}
.cate-title {
  background-color: #fff;
  padding: 20px;
  margin-top: 10px;
}

.cate-btn {
  flex: 1;
  border-width: 1px;
  border-color: $border-color;
  text-align: center;
  font-size: 26px;
  color: #999;
  padding: 10px;
  margin: 5px;
}
.cate-btn-active {
  background-color: $primary;
  color: #fff;
}
</style>
